package com.epfresh.supplier.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.Address;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.api.utils.CustomDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MyAddressActivity extends BaseActivity {
    private ListView mListView;
    private RelativeLayout nodate_ll;
    private TextView nodate_start;

    private TextView lastView;
    private List<Address> mDataList;
    private boolean isFirst;
    Context mContext;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myaddress);
        nodate_start = (TextView)findViewById(R.id.nodate_start);
        nodate_start.setOnClickListener(this);
        mListView = (ListView)findViewById(R.id.listview);
        View llAdd = findViewById(R.id.ll_add);
        mListView.setEmptyView(llAdd);
        mContext = this;
        toolbarTitle.setText("提货地址");
        tvBack.setVisibility(View.VISIBLE);
        ivBack.setVisibility(View.VISIBLE);
//        righticon.setImageDrawable(getResources().getDrawable(R.mipmap.my_add));
//        righticon.setVisibility(View.VISIBLE);
        righticon.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        mHttpLoad();
        super.onResume();
    }

    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.righticon:
            case R.id.nodate_start:
                Intent add = new Intent(getApplicationContext(),
                        NewAddressActivity.class);
                startActivity(add);
                break;
        }
    }

    OnRequestListener<ContentEntity<Address>> onRequestListener = new OnRequestListener<ContentEntity<Address>>() {
        @Override
        public ContentEntity<Address> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<Address>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<Address>> response, Object tag) {
            ContentEntity<Address> addresses = response.getResponseElement();
            mDataList = addresses.getContent();
            mListView.setAdapter(new CommonAdapter<Address>(mContext, mDataList,
                    R.layout.item_adress) {
                @Override
                public int getCount()
                {
                    if(mDatas==null){
                        return 0;
                    }
                    if(mDatas.size()>=1){
                        return 1;
                    }
                    return mDatas.size();
                }
                @Override
                public void convert(final ViewHolder holder, final Address bean) {
                    holder.setText(R.id.address_name, bean.getProvinceName()+bean.getCityName() + bean.getDistrictName()+ bean.getAddress());
                    holder.setText(R.id.name,bean.getContactName());
                    holder.setText(R.id.phone,bean.getTel());
                    holder.setText(R.id.new_name,bean.getName());

                    holder.setOnClickListener(R.id.edit, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent edit = new Intent(getApplicationContext(), NewAddressActivity.class);
                            edit.putExtra("provinceId", bean.getProvinceId());
                            edit.putExtra("cityId", bean.getCityId());
                            edit.putExtra("districtId", bean.getDistrictId());
                            edit.putExtra("provinceName", bean.getProvinceName());
                            edit.putExtra("cityName", bean.getCityName());
                            edit.putExtra("districtName", bean.getDistrictName());
                            edit.putExtra("id", bean.getId());
                            edit.putExtra("accountId", bean.getAccountId());
                            edit.putExtra("address", bean.getAddress());

                            edit.putExtra("name", bean.getName());
                            edit.putExtra("phone", bean.getTel());
                            edit.putExtra("contactName", bean.getContactName());
                            startActivity(edit);
                        }
                    });
                    holder.setOnClickListener(R.id.delete, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                            //new CustomDialog.Builder(mContext)//.setTitle("是否删除")//设置对话框标题
                            //.setMessage("一旦删除，不可更改")//设置显示的内容
                            builder.setTitleVisible(false).setMessage("确定删除地址吗？")//设置显示的内容
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                            mHttpDelete(bean.getId());
                                            dialog.dismiss();
                                        }
                                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//响应事件
                                    dialog.dismiss();
                                    // TODO Auto-generated method stub
                                }

                            });//在按键响应事件中显示此对话框
                            builder.create().show();
                        }
                    });
                }
            });
        }
    };

    /**
     * 加载地址列表数据
     */
    private void mHttpLoad() {

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();

        SharedPreferences user = getSharedPreferences(
                Constant.USERINFO, Activity.MODE_PRIVATE);
        //String token = user.getString("token", "");
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_pickUpAddress_list);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        //data.setToken(token);
        map.put("storeId",BaseApplication.getInstance().getStoreId());
        map.put("merchantId",BaseApplication.getInstance().getMerchantId());
        map.put("accountId", getUser().getAccountId());
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_pickUpAddress_list, onRequestListener);
    }

    /**
     * 删除地址
     */
    private void mHttpDelete(String id) {
//
        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_pickUpAddress_delete);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        //data.setToken(getUser().getToken());
        map.put("id", id);
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_store_store_pickUpAddress_delete, onRequestListenerDelete);
    }

    OnRequestListener<StatusEntity> onRequestListenerDelete = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }
        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                getUser().delDeliveryAddressCount();
               toast(BaseApplication.getDoc().getBeenSubmitted());
                mHttpLoad();
            }else {

            }
        }
    };
    protected void onDestroy() {
        RequestManager.getInstance().cancel("store/pickUpAddress/list");
        RequestManager.getInstance().cancel("store/pickUpAddress/delete");
        super.onDestroy();

    }

    @Override
    protected void onToolbarBack() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        int count = 0;
        if (mDataList!= null){
            count = mDataList.size();
        }
        intent.putExtra("count_pick_up",count);

        if (mDataList != null&& mDataList.size()>0){
            Address address = mDataList.get(0);
            intent.putExtra("pick_up_address",address.getName());
        }
        setResult(RESULT_OK,intent);

        finish();
    }


}
